package zwz.importTask.utils;

import com.alibaba.excel.write.handler.AbstractRowWriteHandler;
import com.alibaba.excel.write.handler.context.RowWriteHandlerContext;
import zwz.importTask.mapper.BiDataImportTaskMapper;
import zwz.importTask.pojo.BiDataImportTaskPO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.concurrent.atomic.AtomicLong;

public class ProgressWriteHandler extends AbstractRowWriteHandler {

    private static final int PROGRESS_UPDATE_INTERVAL = 500; // 每500行记录一次导出进度
    private static final Logger logger = LoggerFactory.getLogger(ProgressWriteHandler.class);

    private AtomicLong rowCounter = new AtomicLong(0);
    private BiDataImportTaskMapper biDataImportTaskMapper;

    public ProgressWriteHandler(BiDataImportTaskMapper biDataImportTaskMapper) {
        this.biDataImportTaskMapper = biDataImportTaskMapper;
    }

    @Override
    public void afterRowDispose(RowWriteHandlerContext context) {
        long currentRow = rowCounter.incrementAndGet();
        // 每5000行记录一次进度
        if (currentRow % PROGRESS_UPDATE_INTERVAL == 0) {
            updateProgress(currentRow);
        }
        super.afterRowDispose(context);
    }

    private void updateProgress(long currentRow) {
        BiDataImportTaskPO biDataImportTaskPO = ImportThreadLocalUtils.getContext().getBiDataImportTaskPO();
        biDataImportTaskPO.setSucceedRecord((int) currentRow);
        biDataImportTaskPO.setModifiedTime(new Date());
        biDataImportTaskMapper.updateById(biDataImportTaskPO);
        logger.info("Updated progress to {} rows", currentRow);
    }
}